package com.kira.scaffoldmvc.Dubbo.Compression.Factory;

import com.kira.scaffoldmvc.Dubbo.Compression.Strategy.CompressionStrategy;
import com.kira.scaffoldmvc.Dubbo.Compression.Strategy.SnappyCompression;
import com.kira.scaffoldmvc.Dubbo.Compression.Strategy.ZipCompression;
import com.kira.scaffoldmvc.Dubbo.Compression.Strategy.ZstdCompression;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
public class CompressionFactory {

    // 从配置文件读取当前启用的算法（默认zstd）
    @Value("${compression.type}")
    private String currentAlgorithm;

    // 算法实例缓存池：key=算法名称（小写），value=对应的压缩实现类
    private final Map<String, CompressionStrategy> strategyMap = new HashMap<>();

    // 初始化：注册所有支持的压缩算法
    public CompressionFactory() {
        // 注册Zstd算法
        strategyMap.put("zstd", new ZstdCompression());
        // 注册Zip算法
        strategyMap.put("zip", new ZipCompression());
        // 后续新增算法只需在这里注册，例如：
        strategyMap.put("gzip", new SnappyCompression());
    }

    /**
     * 获取当前配置的压缩算法实例
     */
    public CompressionStrategy getCurrentStrategy() {
        // 将配置的算法名称转为小写，避免大小写问题
        String algorithm = currentAlgorithm.toLowerCase();
        // 从缓存池获取对应的实例
        CompressionStrategy strategy = strategyMap.get(algorithm);
        
        if (strategy == null) {
            // 如果配置的算法不支持，抛出异常并提示支持的算法
            throw new IllegalArgumentException(
                "不支持的压缩算法: " + currentAlgorithm + 
                "，支持的算法有: " + strategyMap.keySet()
            );
        }
        return strategy;
    }

    /**
     * 手动切换算法（运行时动态切换，不依赖配置文件）
     * @param algorithm 算法名称（如"zstd"、"zip"）
     * @return 对应的压缩算法实例
     */
    public CompressionStrategy switchAlgorithm(String algorithm) {
        if (algorithm == null || algorithm.trim().isEmpty()) {
            throw new IllegalArgumentException("算法名称不能为空");
        }
        CompressionStrategy strategy = strategyMap.get(algorithm.toLowerCase());
        if (strategy == null) {
            throw new IllegalArgumentException("不支持的压缩算法: " + algorithm);
        }
        return strategy;
    }
}